<template>
  <view class="sdk-test-page">
    <view class="header">
      <text class="title">SDK 错误监控测试</text>
    </view>

    <view class="test-section">
      <view class="section-title">基础功能测试</view>

      <button @click="testJSError" class="test-btn error-btn">
        测试 JS 错误
      </button>

      <button @click="testPromiseRejection" class="test-btn warning-btn">
        测试 Promise 拒绝
      </button>

      <button @click="testCustomError" class="test-btn info-btn">
        测试自定义错误
      </button>
    </view>

    <view class="test-section">
      <view class="section-title">用户行为追踪测试</view>

      <button @click="testUserBehavior" class="test-btn success-btn">
        记录自定义用户行为
      </button>

      <button @click="testClickTracking" class="test-btn">测试点击追踪</button>

      <button @click="testFormInteraction" class="test-btn">
        测试表单交互
      </button>

      <button @click="testNavigationTracking" class="test-btn">
        测试页面导航
      </button>

      <button @click="showBehaviorHistory" class="test-btn info-btn">
        查看行为历史
      </button>
    </view>

    <view class="test-section">
      <view class="section-title">配置测试</view>

      <button @click="setUserId" class="test-btn">设置用户ID</button>

      <button @click="setCustomFields" class="test-btn">设置自定义字段</button>
    </view>

    <view class="test-section">
      <view class="section-title">平台特定测试</view>

      <button @click="testNetworkError" class="test-btn">测试网络错误</button>

      <button @click="testResourceError" class="test-btn">
        测试资源加载错误
      </button>
    </view>

    <!-- 测试表单 -->
    <view class="test-section" v-if="showTestForm">
      <view class="section-title">测试表单</view>
      <input
        v-model="testInput"
        placeholder="输入测试内容"
        class="test-input"
        @input="onInputChange"
        @focus="onInputFocus"
        @blur="onInputBlur"
      />
      <button @click="submitTestForm" class="test-btn">提交表单</button>
    </view>

    <view class="logs">
      <view class="section-title">测试日志</view>
      <view class="log-item" v-for="(log, index) in logs" :key="index">
        <text class="log-time">{{ log.time }}</text>
        <text class="log-content">{{ log.content }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
import { UniErrorSDK, ErrorLevel } from "@logwisdomhub/uniapp-error-sdk";
import PLATFORM from "@/utils/platform";
const logs = ref<Array<{ time: string; content: string }>>([]);
const showTestForm = ref(false);
const testInput = ref("");
const { isH5, isApp, isMp, isMpWeixin } = PLATFORM;

console.log(isApp ? "App" : isMpWeixin ? "Weixin" : "H5",'1233')
// 创建 SDK 实例
const errorSDK = new UniErrorSDK({
  apiKey:
    "lwh_3a880a5346ebf75eecd30d8f8fffefe43521ecb5717b0b659261fd889027339e",
  baseURL: "http://192.168.1.21:8001",
  projectId: "6",
  platform: isApp ? "App" : isMpWeixin ? "Weixin" : "H5", // 添加platform配置
  enableConsoleLog: true,
  enableAutoReport: true,
  enableUserBehavior: true, // 启用用户行为追踪
  maxRetryCount: 3,
  retryDelay: 1000,
});

// 初始化 SDK
onMounted(async () => {
  try {
    await errorSDK.init();
    addLog("SDK 初始化成功，用户行为追踪已启用");
  } catch (error) {
    addLog("SDK 初始化失败: " + error);
  }
});

function addLog(content: string) {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    content,
  });
  console.log(`[SDK Test] ${content}`);
}

// 测试JS错误
function testJSError() {
  try {
    addLog("触发JS错误测试");
    const obj: any = null;
    obj.nonExistentMethod();
  } catch (error) {
    // 使用实例调用方法
    errorSDK.reportError(error as Error, ErrorLevel.ERROR, {
      testType: "manual-js-error",
      userAction: "click-test-button",
      tags: ["test", "js-error"],
    });
    addLog("JS错误已报告到SDK");
  }
}

// 测试Promise拒绝
function testPromiseRejection() {
  addLog("触发Promise拒绝测试");
  Promise.reject(new Error("测试Promise拒绝错误")).catch((error) => {
    errorSDK.reportError(error, ErrorLevel.WARNING, {
      tags: ["test", "promise-rejection"],
    });
    addLog("Promise拒绝错误已报告到SDK");
  });
}

// 测试自定义错误
function testCustomError() {
  addLog("触发自定义错误测试");
  const customError = new Error("这是一个自定义测试错误");
  errorSDK.reportError(customError, ErrorLevel.INFO, {
    customField1: "自定义值1",
    customField2: 42,
    testEnvironment: "unibest-development",
    tags: ["test", "custom-error"],
  });
  addLog("自定义错误已报告到SDK");
}

// 测试用户行为记录
function testUserBehavior() {
  addLog("记录自定义用户行为");
  // 使用SDK的recordCustomBehavior方法
  errorSDK.recordCustomBehavior("test_action", {
    action: "用户点击测试按钮",
    page: "sdk-test",
    timestamp: Date.now(),
    userAgent: navigator.userAgent || "unknown",
  });
  addLog("自定义用户行为已记录");
}

// 测试点击追踪
function testClickTracking() {
  addLog("测试点击追踪功能");
  // 使用SDK的recordClick方法
  errorSDK.recordClick({
    type: "button",
    id: "test-click-btn",
    text: "测试点击追踪",
    position: { x: 100, y: 200 },
    page: "sdk-test",
  });
  addLog("点击事件已记录到用户行为");
}

// 测试表单交互
function testFormInteraction() {
  showTestForm.value = !showTestForm.value;
  addLog(showTestForm.value ? "显示测试表单" : "隐藏测试表单");
}

// 表单输入事件
function onInputChange() {
  errorSDK.recordCustomBehavior("input", {
    type: "input_change",
    field: "test_input",
    value_length: testInput.value.length,
    page: "sdk-test",
  });
}

function onInputFocus() {
  errorSDK.recordCustomBehavior("form", {
    type: "input_focus",
    field: "test_input",
    page: "sdk-test",
  });
  addLog("输入框获得焦点");
}

function onInputBlur() {
  errorSDK.recordCustomBehavior("form", {
    type: "input_blur",
    field: "test_input",
    page: "sdk-test",
  });
  addLog("输入框失去焦点");
}

function submitTestForm() {
  errorSDK.recordCustomBehavior("form", {
    type: "form_submit",
    form_data: { test_input: testInput.value },
    page: "sdk-test",
  });
  addLog("表单提交行为已记录");
  testInput.value = "";
  showTestForm.value = false;
}

// 测试页面导航
function testNavigationTracking() {
  addLog("测试页面导航追踪");
  // 记录导航意图
  errorSDK.recordCustomBehavior("navigate", {
    type: "navigation_intent",
    from: "sdk-test",
    to: "index",
    trigger: "user_click",
  });

  // 模拟导航（实际项目中会自动追踪）
  setTimeout(() => {
    uni.navigateTo({
      url: "/pages/index/index",
    });
  }, 1000);
}

// 查看行为历史
function showBehaviorHistory() {
  const behaviors = errorSDK.getUserBehavior();
  const sessionInfo = errorSDK.getSessionInfo();

  addLog(
    `当前会话信息: 持续时间${Math.floor(sessionInfo.sessionDuration / 1000)}秒，行为数量${sessionInfo.behaviorCount}个`,
  );
  addLog(
    `最近的用户行为: ${behaviors
      .slice(0, 3)
      .map((b) => `${b.type}(${new Date(b.timestamp).toLocaleTimeString()})`)
      .join(", ")}`,
  );

  console.log("完整行为历史:", behaviors);
  console.log("会话信息:", sessionInfo);
}

// 设置用户ID
function setUserId() {
  const userId = `user_${Date.now()}`;
  // 注意：当前SDK版本可能需要在初始化时设置，这里演示概念
  errorSDK.recordCustomBehavior("session", {
    type: "user_id_set",
    user_id: userId,
    page: "sdk-test",
  });
  addLog(`用户ID已设置: ${userId}`);
}

// 设置自定义字段
function setCustomFields() {
  const customData = {
    test_environment: "unibest-development",
    feature_flags: ["user_behavior_tracking", "error_monitoring"],
    user_role: "tester",
  };

  errorSDK.recordCustomBehavior("session", {
    type: "custom_fields_set",
    custom_data: customData,
    page: "sdk-test",
  });
  addLog("自定义字段已设置");
}

// 测试网络错误
function testNetworkError() {
  addLog("测试网络错误");
  uni.request({
    url: "https://nonexistent-domain-for-testing.com/api/test",
    success: () => {
      addLog("网络请求成功（不应该发生）");
    },
    fail: (error) => {
      errorSDK.reportError(
        new Error(`网络请求失败: ${error.errMsg}`),
        ErrorLevel.ERROR,
        {
          url: "https://nonexistent-domain-for-testing.com/api/test",
          errorMsg: error.errMsg,
          tags: ["test", "network-error"],
        },
      );
      addLog("网络错误已报告到SDK");
    },
  });
}

// 测试资源加载错误
function testResourceError() {
  addLog("测试资源加载错误");
  const error = new Error("图片资源加载失败");
  errorSDK.reportError(error, ErrorLevel.WARNING, {
    resourceType: "image",
    resourceUrl: "/static/nonexistent-image.png",
    tags: ["test", "resource-error"],
  });
  addLog("资源加载错误已报告到SDK");
}
</script>

<style scoped>
.sdk-test-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.test-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.test-btn {
  width: 100%;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 6px;
  border: none;
  font-size: 16px;
  color: white;
  background-color: #007aff;
}

.error-btn {
  background-color: #ff3b30;
}

.warning-btn {
  background-color: #ff9500;
}

.info-btn {
  background-color: #007aff;
}

.success-btn {
  background-color: #34c759;
}

.logs {
  background: white;
  border-radius: 8px;
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.log-item {
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.log-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.log-content {
  font-size: 14px;
  color: #333;
}

.test-input {
  width: 100%;
  padding: 12px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}
</style>
